<?php
/**
 * Here is your custom functions.
 */

use plugin\muadmin\app\common\model\AdminConfig;
use Webman\Event\Event;
use Workerman\Timer;
use Workerman\Worker;

/**
 * 检查目录及其子目录的权限
 * @param string $dir 要检查的目录路径
 * @return void
 */
function checkDirPermissions($dir, $data = [])
{
    if (!is_dir($dir)) {
        throw new \RuntimeException(sprintf('指定的路径 "%s" 不是一个有效的目录', $dir));
    }

    if (empty($data)) {
        $data = [
            'unreadable' => [],
            'not_writable' => []
        ];
    }

    try {
        if (!is_readable($dir)) {
            $data['unreadable'][] = $dir;
        }
        if (!is_writable($dir)) {
            $data['not_writable'][] = $dir;
        }
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                $fullPath = $dir . DIRECTORY_SEPARATOR . $file;
                // 判断是否为目录，如果是则递归调用
                if (is_dir($fullPath)) {
                    $data = checkDirPermissions($fullPath, $data); // 递归调用自身来检查子目录
                } else {
                    // 如果是文件，则检查其读写权限
                    if (!is_readable($fullPath)) $data['unreadable'][] = $fullPath;
                    if (!is_writable($fullPath)) $data['not_writable'][] = $fullPath;
                }
            }
            closedir($dh);
        }
        return $data;
    } catch (Exception $e) {
        $data['unreadable'][] = $dir;
        $data['not_writable'][] = $dir;
        return $data;
    }
}

/**
 * 获取随机字符串
 */
if (!function_exists('random_str')) {
    function random_str(int $length = 4, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    {
        if ($length < 1) {
            return "";
        }
        $pieces = [];
        $max = mb_strlen($keyspace, '8bit') - 1;
        for ($i = 0; $i < $length; ++$i) {
            $pieces [] = $keyspace[random_int(0, $max)];
        }
        return implode('', $pieces);
    }
}
/**
 * 创建密码
 */
if (!function_exists('create_password')) {
    function create_password($password, $salt)
    {
        return password_hash($password . $salt, PASSWORD_DEFAULT);
    }
}
/**
 * 验证密码
 */
if (!function_exists('verify_password')) {
    function verify_password($password, $hash, $salt)
    {
        return password_verify($password . $salt, $hash);
    }
}
/**
 * 列表转树形结构
 */
if (!function_exists('list_to_tree')) {
    function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parent_id = $data[$pid];
                if ($root == $parent_id) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parent_id])) {
                        $parent =& $refer[$parent_id];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}

/**
 * 获取配置
 */
if(!function_exists('config_mu')){
    function config_mu($key=null,$default='')
    {
        if(empty($key)){
            return $default;
        }
        $keyArray = explode('.',$key);
        $keyArray = array_values(array_filter($keyArray));
        if(!isset($keyArray[0])){
            return $default;
        }
        $adminArray = AdminConfig::where('group', $keyArray[0])
            ->field('name,value')
            ->select()->toArray();
        if(empty($adminArray)){
            return $default;
        }
        if(!empty($adminArray)){
            $adminArray = array_column($adminArray,'value','name');
        }else{
            return $default;
        }
        if(count($keyArray)==1){
            return $adminArray;
        }
        if(!empty($keyArray[1])){
            if(isset($adminArray[$keyArray[1]])){
                return $adminArray[$keyArray[1]];
            }
        }
        if(!empty($keyArray[2])){
            if(is_string($adminArray[$keyArray[1]])){
                $adminArray = json_decode($adminArray[$keyArray[1]],true);
                if(empty($adminArray)){
                    return $default;
                }
            }
            if(isset($adminArray[$keyArray[1]][$keyArray[2]])){
                return $adminArray[$keyArray[1]][$keyArray[2]];
            }
        }
        return $default;
    }
}
/**
 * 上传文件
 */
if(!function_exists('upload_file')){
    function upload_file($config,$file,$savePath = '')
    {
        /// 本地上传
        $suffix = $file->getUploadExtension();
        $mimetype = $file->getUploadMimeType();
        $ext_forbidden_map = ['php', 'php3', 'php5', 'css', 'js', 'html', 'htm', 'asp', 'jsp'];
        if (in_array($mimetype, $ext_forbidden_map)) {
            throw new Exception('上传文件格式错误');
        }
        $filename = $file->getUploadName();
        $filesize = $file->getSize();
        if(isset($config['mimetype'])&&is_array($mimetype)&&!in_array($mimetype,$config['mimetype'])){
            throw new \Exception('上传文件格式错误');
        }
        if(empty($savePath)){
            $array = [
                '{plugin}'=>request()->plugin,
                '{year}'=>date('Y'),
                '{mon}'=>date('m'),
                '{day}'=>date('d'),
                '{filemd5}'=>md5($filename),
                '{.suffix}'=>'.'.$suffix,
            ];
            if(empty($config['savekey'])){
                $config['savekey'] = '/plugin/{plugin}/public/uploads/{year}{mon}{day}/{filemd5}{.suffix}';
            }
            $savePath = str_replace(array_keys($array),array_values($array),$config['savekey']);
        }
        $saveName = str_replace('plugin','app',$savePath);
        $saveName = str_replace('public/','',$saveName);
        $savePath = base_path().$savePath;
//            print_r($savePath);
        if(!is_dir(dirname($savePath))){
            mkdir(dirname($savePath), 0755, true);
        }
        $back = [
            'mimetype'=>$mimetype,
            'filesize'=>$filesize,
            'url'=>$saveName,
            'fullurl'=>cdnurl($saveName),
            'imagewidth'=>0,
            'imageheight'=>0,
            'sha1'=>md5($filename),
            'storage'=>'local'
        ];
        if(empty($config['class_name'])||(isset($config['driver'])&&$config['driver']=='local')||empty($config['driver'])){

            $res = $file->move($savePath);
            if($res){
                if ($img_info = getimagesize($savePath)) {
                    [$image_with, $image_height] = $img_info;
                    $back['imagewidth'] = $image_with;
                    $back['imageheight'] = $image_height;
                }
            }else{
                throw new \Exception($file->getError());
            }
            return $back;
        }else{
            ///  第三方上传
            $obj = new $config['class_name']($config);
            if(method_exists($obj,'save')){
                $obj->save($file,$filename);
            }else{
                throw new \Exception('上传类不存在save方法');
            }
            if ($img_info = getimagesize($file->getRealPath())) {
                [$image_with, $image_height] = $img_info;
                $back['imagewidth'] = $image_with;
                $back['imageheight'] = $image_height;
            }
            return $back;
        }
    }
}
/**
 * 获取cdn地址
 */
if(!function_exists('cdnurl')){
    function cdnurl($filePath='',$domain=true)
    {
        if(empty($filePath)){
            return $filePath;
        }
        if(strpos($filePath,'http')===0){
            return $filePath;
        }
        if(strpos($filePath,"base64")){
            return $filePath;
        }
        if($domain===false){
            return $filePath;
        }
        $config = config('plugin.muadmin.upload');
        $event_config = Event::emit('get_upload_config',[]);
        foreach ($event_config as $item){
            if(!empty($item['upload'])&&is_array($item['upload'])){
                $config = array_merge($config,$item['upload']);
            }
        }
        if(!empty($config['cdnurl'])){
            return ltrim($config['cdnurl'],'/').'/'.$filePath;
        }
        return request()->header('origin').$filePath;
    }
}
/**
 * 语言翻译
 */
if(!function_exists('__')){
    function __($name)
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        return trans($name);
    }
}
/**
 * 获取插件模块
 */
if(!function_exists('get_plugin_module')){
    function get_plugin_module($plugin)
    {
        $dir = base_path().'/plugin/'.$plugin.'/app/';
//        print_r($dir);
        if(!is_dir($dir)){
            return [];
        }
        return get_dir_path($dir,'dir');
    }
}
/**
 * 获取目录
 */
if(!function_exists('get_dir_path')){
    function get_dir_path(string $dir,string $type="all",array $excluded=[],array $only = [],bool $has_child=false,bool $is_path=false)
    {
        if(!is_dir($dir)&&!is_file($dir)){
            return [];
        }
        $dir = str_replace('\\', '/', $dir);
        $dir = rtrim($dir,'/').'/';
        $dirsList = scandir($dir);
        $dirsList = array_filter($dirsList,function($item){
            return $item!='.'&&$item!='..';
        });
        $all = [];
        $filter = function ($dir,$item)use($type,$excluded,$only,$is_path){
            $path = $dir.$item;
            if(!empty($excluded)){
                if(in_array($item,$excluded)){
                    return [];
                }
            }
            if(!empty($only)){
                if(!in_array($item,$only)){
                    return [];
                }
            }
            if($type!='all'){
                if($type=='dir'&&!is_dir($path)){
                    return [];
                }
                if($type=='file'&&is_dir($path)){
                    return [];
                }
            }
            if($is_path){
                return $path;
            }else{
                return $item;
            }
        };
        foreach ($dirsList as $key => $value){
            if($has_child){
                if(is_dir($dir.$value)){
                    $tem = $filter($dir,$value);
                    if(!empty($tem)){
                        $all[] = $tem;
                    }
                    $all = array_merge($all,get_dir_path(dir:$dir.$value,type:$type,excluded: $excluded,only: $only,has_child: $has_child,is_path: $is_path));
                }else{
                    $tem = $filter($dir,$value);
                    if(!empty($tem)){
                        $all[] = $tem;
                    }
                }
            }else{
                $tem = $filter($dir,$value);
                if(!empty($tem)){
                    $all[] = $tem;
                }
            }
        }
        $all = array_unique($all);
        return $all;
    }
}
/**
 * 删除目录
 */
if(!function_exists('delete_dir')){
    function delete_dir($src)
    {
        $dir = opendir($src);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                $full = $src . '/' . $file;
                if (is_dir($full)) {
                    delete_dir($full);
                } else {
                    unlink($full);
                }
            }
        }
        closedir($dir);
        rmdir($src);
        return true;
    }
}
/**
 * 重载webman
 */
if(!function_exists('reloadWebman')){
    function reloadWebman()
    {
        if (function_exists('posix_kill')) {
            try {
                posix_kill(posix_getppid(), SIGUSR1);
                return true;
            } catch (Throwable $e) {}
        } else {
            Timer::add(1, function () {
                Worker::stopAll();
            });
        }
    }
}
